package com.base.huidu;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;

public class Json
{
	public static void main(String[] args) throws JSONException {
		
		String json = "[{\"id\":1,\"book_name\":\"\u4e16\u754c\u4e0a\u6700\u4f1f\u5927\u7684\u63a8\u9500\u5458\",\"down_url\":\"\u4e16\u754c\u4e0a\u6700\u4f1f\u5927\u7684\u63a8\u9500\u5458.txt\"}]";
		JSONArray ja = new JSONArray(json);
		int iSize = ja.length();

		for (int i=0; i<iSize ; i++)
		{
			JSONObject jo = ja.getJSONObject(i);
			System.out.println("id : " + jo.get("id"));
			System.out.println("book_name : " + jo.get("book_name"));
			System.out.println();
		}

	}
	
	public static ArrayList<Book> getBookList(String url, String encoding) throws Exception
	{
		String json = getNetString(url, encoding);
		JSONArray ja = new JSONArray(json);
		int iSize = ja.length();
		ArrayList<Book> al = new ArrayList<Book>();
		for(int i=0; i < iSize; i++)
		{
			JSONObject jo = ja.getJSONObject(i);
			Book b = new Book();
			b.setBookName(jo.getString("book_name"));
			b.setId(jo.getInt("id"));
			b.setDownloadUrl(jo.getString("download_url"));
			al.add(b);
		}
		return al;
	}
	
	public static String getNetString(String path, String encoding) throws Exception
	{
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		conn.setConnectTimeout(6*1000);
		
		if(conn.getResponseCode() == 200)
		{
			InputStream inputStream = conn.getInputStream();
			byte[] data = readStream(inputStream);
			
			return new String(data, encoding);
		}
		return null;
		
	}
	
	public static byte[] readStream(InputStream inStream) throws Exception
	{
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = -1;
		while((len = inStream.read(buffer)) != -1)
		{
			outStream.write(buffer, 0, len);
		}
		outStream.close();
		inStream.close();
		return outStream.toByteArray();
	}
}